package com.example.code.nas;

import cn.hutool.extra.ftp.FtpException;
import cn.hutool.extra.ssh.JschUtil;
import cn.hutool.extra.ssh.Sftp;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

public class NASUtil {
    public static final String NAS_IP = "210.29.66.192";
    public static final int NAS_PORT = 2222;
    public static final String NAS_USERNAME = "econtract";
    public static final String NAS_PASSWORD = "NhE^~cXWEqnB3^BW$e9F";

    public static void main222(String[] args) throws FileNotFoundException {
        Session sessionLinux = JschUtil.getSession(NAS_IP, NAS_PORT, NAS_USERNAME, NAS_PASSWORD);
        Sftp sftp = JschUtil.createSftp(sessionLinux);

        // 创建文件夹
        String linuxPath = "/opt/econtract/nas/202306";
        sftp.mkdir(linuxPath);

        String wjml = "D:\\DATA\\Documents\\常用上传文件\\5合同文件2.pdf";
        File file = new File(wjml);
//        sftp.cd(linuxPath);
        sftp.put(file.getPath(), linuxPath + "合同文件4.pdf");

        sftp.close();
        System.out.println("over");

        sftp.ls("");
    }

    public static void main(String[] args) throws JSchException {
        Session sessionLinux = JschUtil.getSession(NAS_IP, NAS_PORT, NAS_USERNAME, NAS_PASSWORD);
        Sftp sftp = JschUtil.createSftp(sessionLinux);


        List<String> stringList = sftp.ls("/opt/econtract/nas/2024-08-23");
        for (String s : stringList) {
            System.out.println(s);
        }

        sftp.close();
        System.out.println("over");

    }

    public static void main2(String[] args) throws IOException, JSchException {
        Session sessionLinux = JschUtil.getSession(NAS_IP, NAS_PORT, NAS_USERNAME, NAS_PASSWORD);
        Sftp sftp = JschUtil.createSftp(sessionLinux);
        String directory = "/opt/econtract/nas/202306";

        sftpMkdir(sftp, directory);

        String wjml = "D:\\DATA\\Pictures\\QQ图片20220531154231.jpg";
        String destPath = directory + "QQ图片20220531154231.jpg";
        sftp.put(wjml, destPath);

        sftp.close();
        System.out.println("over");

    }


    /**
     * 创建文件夹 ，添加是否存在的判断
     *
     * @param sftp
     * @param path
     */
    public static void sftpMkdir(Sftp sftp, String path) {
        ChannelSftp client = sftp.getClient();
        boolean isDir = true;
        try {
            SftpATTRS stat = client.stat(path);
        } catch (SftpException e) {
            if (e.getMessage().contains("No such file")) {
                // 文件不存在直接返回false
                isDir = false;
            } else {
                throw new FtpException(e);
            }
        }
        if (!isDir) {
            sftp.mkdir(path);
        }
    }

}
